import { isDevelopment } from '@/config/env'

// API响应结果包装器
export class ApiResponse {
  constructor(success, data, message = '', code = 200) {
    this.success = success
    this.data = data
    this.message = message
    this.code = code
    this.timestamp = new Date().toISOString()
  }

  static success(data, message = '操作成功') {
    return new ApiResponse(true, data, message)
  }

  static error(message = '操作失败', code = 500) {
    return new ApiResponse(false, null, message, code)
  }
}

// 分页参数构建器
export class PaginationBuilder {
  constructor(page = 1, pageSize = 10) {
    this.page = page
    this.pageSize = pageSize
    this.sortBy = null
    this.sortOrder = 'asc'
    this.filters = {}
  }

  setPage(page) {
    this.page = page
    return this
  }

  setPageSize(pageSize) {
    this.pageSize = pageSize
    return this
  }

  setSort(sortBy, sortOrder = 'asc') {
    this.sortBy = sortBy
    this.sortOrder = sortOrder
    return this
  }

  addFilter(key, value) {
    this.filters[key] = value
    return this
  }

  addFilters(filters) {
    Object.assign(this.filters, filters)
    return this
  }

  build() {
    const params = {
      page: this.page,
      pageSize: this.pageSize
    }

    if (this.sortBy) {
      params.sortBy = this.sortBy
      params.sortOrder = this.sortOrder
    }

    return { ...params, ...this.filters }
  }
}

// 搜索参数构建器
export class SearchBuilder {
  constructor(keyword = '') {
    this.keyword = keyword
    this.filters = {}
    this.dateRange = null
  }

  setKeyword(keyword) {
    this.keyword = keyword
    return this
  }

  addFilter(key, value) {
    this.filters[key] = value
    return this
  }

  setDateRange(startDate, endDate) {
    this.dateRange = { startDate, endDate }
    return this
  }

  build() {
    const params = { keyword: this.keyword, ...this.filters }
    
    if (this.dateRange) {
      params.startDate = this.dateRange.startDate
      params.endDate = this.dateRange.endDate
    }

    return params
  }
}

// API错误处理工具
export class ApiErrorHandler {
  static handle(error, customMessage = '') {
    if (isDevelopment) {
      console.error('API Error Details:', error)
    }

    let message = customMessage

    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 400:
          message = data?.message || '请求参数错误'
          break
        case 401:
          message = '未授权，请重新登录'
          break
        case 403:
          message = '权限不足'
          break
        case 404:
          message = '请求的资源不存在'
          break
        case 422:
          message = data?.message || '数据验证失败'
          break
        case 500:
          message = '服务器内部错误'
          break
        default:
          message = data?.message || '请求失败'
      }
    } else if (error.request) {
      message = '网络连接失败，请检查网络设置'
    } else {
      message = error.message || '未知错误'
    }

    return message
  }

  static async withErrorHandling(apiCall, customMessage = '') {
    try {
      return await apiCall()
    } catch (error) {
      const message = this.handle(error, customMessage)
      throw new Error(message)
    }
  }
}

// 文件上传工具
export class FileUploadHelper {
  static createFormData(files, additionalData = {}) {
    const formData = new FormData()
    
    if (Array.isArray(files)) {
      files.forEach((file, index) => {
        formData.append(`files[${index}]`, file)
      })
    } else {
      formData.append('file', files)
    }

    // 添加额外数据
    Object.keys(additionalData).forEach(key => {
      formData.append(key, additionalData[key])
    })

    return formData
  }

  static validateFile(file, options = {}) {
    const {
      maxSize = 10 * 1024 * 1024, // 默认10MB
      allowedTypes = [],
      allowedExtensions = []
    } = options

    // 检查文件大小
    if (file.size > maxSize) {
      throw new Error(`文件大小不能超过 ${maxSize / 1024 / 1024}MB`)
    }

    // 检查文件类型
    if (allowedTypes.length > 0 && !allowedTypes.includes(file.type)) {
      throw new Error(`不支持的文件类型: ${file.type}`)
    }

    // 检查文件扩展名
    if (allowedExtensions.length > 0) {
      const extension = file.name.split('.').pop().toLowerCase()
      if (!allowedExtensions.includes(extension)) {
        throw new Error(`不支持的文件格式: .${extension}`)
      }
    }

    return true
  }
}

// 缓存工具
export class ApiCache {
  constructor() {
    this.cache = new Map()
    this.defaultTTL = 5 * 60 * 1000 // 5分钟
  }

  set(key, data, ttl = this.defaultTTL) {
    const expiresAt = Date.now() + ttl
    this.cache.set(key, { data, expiresAt })
  }

  get(key) {
    const item = this.cache.get(key)
    if (!item) return null

    if (Date.now() > item.expiresAt) {
      this.cache.delete(key)
      return null
    }

    return item.data
  }

  delete(key) {
    this.cache.delete(key)
  }

  clear() {
    this.cache.clear()
  }

  has(key) {
    return this.cache.has(key) && Date.now() <= this.cache.get(key).expiresAt
  }
}

// 导出工具实例
export const paginationBuilder = new PaginationBuilder()
export const searchBuilder = new SearchBuilder()
export const apiCache = new ApiCache()

export default {
  ApiResponse,
  PaginationBuilder,
  SearchBuilder,
  ApiErrorHandler,
  FileUploadHelper,
  ApiCache,
  paginationBuilder,
  searchBuilder,
  apiCache
} 